package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/3/15 13:19
 */
public class SelectLocationMapFragment extends BaseFragment
    implements LocationSource, AMapLocationListener, AMap.OnCameraChangeListener,
    GeocodeSearch.OnGeocodeSearchListener, AMap.OnMapClickListener {
  public static final String EXTRA_LAT =
      SelectLocationMapFragment.class.getSimpleName() + "EXTRA_LAT";
  public static final String EXTRA_LON =
      SelectLocationMapFragment.class.getSimpleName() + "EXTRA_LON";
  public static final String EXTRA_ADDRESS =
      SelectLocationMapFragment.class.getSimpleName() + "EXTRA_ADDRESS";
  @BindView(R.id.tv_loc) TextView tvLoc;
  @BindView(R.id.mv_map) MapView mvMap;
  //private String mAddress;
  //private String mLat;
  //private String mLon;
  private AMap mMap;
  private OnLocationChangedListener mListener;
  private AMapLocationClient mlocationClient;
  private LatLng mLatLng;
  private Marker mMarker;
  private GeocodeSearch mGeocoderSearch;
  private boolean isFinishActivity;
  private String mAddress;
    /*是否刷新marker的位置,默认第一次时刷新*/
  //private boolean isRefreshLocation = true;

  public static Fragment newInstance(String address, String regionX, String regionY) {
    SelectLocationMapFragment fragment = new SelectLocationMapFragment();
    Bundle args = new Bundle();
    args.putString(EXTRA_ADDRESS, address);
    args.putString(EXTRA_LAT, regionX);
    args.putString(EXTRA_LON, regionY);
    fragment.setArguments(args);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitleCustom(getString(R.string.selectLocation));
    mAddress = getArguments().getString(EXTRA_ADDRESS);
    String mLat = getArguments().getString(EXTRA_LAT);
    String mLon = getArguments().getString(EXTRA_LON);
    double lat = MyUtils.valueOfDouble(mLat, 0);
    double lon = MyUtils.valueOfDouble(mLon, 0);
    mLatLng = new LatLng(lat, lon);
    mGeocoderSearch = new GeocodeSearch(mActivity);
    mGeocoderSearch.setOnGeocodeSearchListener(this);
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_select_location_map, container, false);
    ButterKnife.bind(this, view);
    initData(savedInstanceState);
    return view;
  }

  @Override public void onResume() {
    super.onResume();
    //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
    mvMap.onResume();
  }

  @Override public void onPause() {
    super.onPause();
    //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
    mvMap.onPause();
  }

  @Override public void onDestroy() {
    super.onDestroy();
    //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
    mvMap.onDestroy();
    if (null != mlocationClient) {
      mlocationClient.onDestroy();
    }
  }

  private void initData(Bundle savedInstanceState) {
    mvMap.onCreate(savedInstanceState);
    mMap = mvMap.getMap();
    mMap.setOnCameraChangeListener(this);
    mMap.setOnMapClickListener(this);
    if (mLatLng.latitude != 0) {
      initMarker(mLatLng);  //更新地图.
      tvLoc.setText(mAddress);
    } else {
      mMap.setLocationSource(this);   // 设置定位监听
      mMap.setMyLocationEnabled(true);
    }
  }

  private void initMarker(LatLng latLng) {
    if (latLng == null) return;
    mMarker = mMap.addMarker(new MarkerOptions().position(latLng));
    CameraUpdate cameraUpdate =
        CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng,//新的中心点坐标
            15, //新的缩放级别
            0, //俯仰角0°~45°（垂直与地图时为0）
            0  ////偏航角 0~360° (正北方为0)
        ));
    mMap.animateCamera(cameraUpdate);
    mMarker.showInfoWindow();
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_confirm, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_item_confirm:
        //ToastUtil.show("确认");
        MyUtils.showDialogLoading(mActivity);
        isFinishActivity = true;//结束当前页面
        updateLocation(mLatLng.latitude, mLatLng.longitude);
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
    mvMap.onSaveInstanceState(outState);
  }

  @Override public void activate(OnLocationChangedListener listener) {
    mListener = listener;
    if (mlocationClient == null) {
      //初始化定位
      mlocationClient = new AMapLocationClient(mActivity);
      //初始化定位参数
      AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
      //设置定位回调监听
      mlocationClient.setLocationListener(this);
      //设置为高精度定位模式
      mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
      //设置定位参数
      mlocationClient.setLocationOption(mLocationOption);
      // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
      // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
      // 在定位结束后，在合适的生命周期调用onDestroy()方法
      // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
      mlocationClient.startLocation();//启动定位
    }
  }

  @Override public void deactivate() {
    mListener = null;
    if (mlocationClient != null) {
      mlocationClient.stopLocation();
      mlocationClient.onDestroy();
    }
    mlocationClient = null;
  }

  @Override public void onLocationChanged(AMapLocation amapLocation) {
    if (amapLocation == null || mListener == null) return;
    if (amapLocation.getErrorCode() != 0) {
      String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
      LogUtil.e("AmapErr", errText);
      return;
    }
    //定位成功
    mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
    if (mLatLng.latitude == 0) {
      //只要一次定位成功,更新地图后就可以关闭设置marker的方法了.
      mLatLng = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
      initMarker(new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude()));
    }
  }

  @Override public void onCameraChange(CameraPosition cameraPosition) {
    if (mMarker == null || cameraPosition == null) return;
    updateMarker(cameraPosition.target);
  }

  @Override public void onCameraChangeFinish(CameraPosition cameraPosition) {
    //if (mMarker == null || cameraPosition == null) return;
    //updateMarker(cameraPosition.target);
    if (mMarker == null || cameraPosition == null || cameraPosition.target == null) return;
    updateLocation(cameraPosition.target.latitude, cameraPosition.target.longitude);
  }

  private void updateMarker(LatLng latLng) {
    if (latLng == null) return;
    mLatLng = latLng;
    mMarker.setPosition(latLng);
    //updateLocation(this.mLatLng.latitude, this.mLatLng.longitude);
  }

  private void updateLocation(double lat, double lng) {
    LatLonPoint latLonPoint = new LatLonPoint(lat, lng);
    // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
    RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
    // 设置同步逆地理编码请求
    mGeocoderSearch.getFromLocationAsyn(query);
  }

  @Override public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
    MyUtils.dismissDialog();
    try {
      String address = regeocodeResult.getRegeocodeAddress().getFormatAddress() + "附近";
      tvLoc.setText(address);
      if (!isFinishActivity) return;
      Intent intent = new Intent();
      intent.putExtra(EXTRA_ADDRESS, address);
      intent.putExtra(EXTRA_LAT, String.valueOf(mLatLng.latitude));
      intent.putExtra(EXTRA_LON, String.valueOf(mLatLng.longitude));
      mActivity.setResult(Activity.RESULT_OK, intent);
      mActivity.finish();
    } catch (Exception e) {
      //e.printStackTrace();
      ToastUtil.show("获取位置信息失败!");
    }
  }

  @Override public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

  }

  @Override public void onMapClick(LatLng latLng) {
    updateMarker(latLng);
    if (latLng == null) return;
    updateLocation(latLng.latitude, latLng.longitude);
  }
}
